//
//  CharacterViewController.m
//  PacIsBack
//
//  Created by Jérémy Brault on 21/01/10.
//  Copyright 2010 None. All rights reserved.
//

#import "CharacterViewController.h"
#import "CharacterBattleAnimationController.h"
#import "CharacterProtocol.h"
#import "CharacterView.h"
#import "LifeBarViewController.h"
#import "RPGImageView.h"
#import "Constants.h"
#import "BattleProtocol.h"

@implementation CharacterViewController

@synthesize character,spritesMoveLeft,spritesMoveRight,spritesSelected,spritesStand,spritesAttack,currentAnim,indexOfCurrentImage,originalPosition,animationTimer,
spriteAnimationActive,spriteAnimationMustLoop,selectorSpriteAnimationEnded,characterPerformingAnimation,targetForSelectorSpriteAnimationEnded,animationController, currentFrameView, lifeBarsController, currentDamagesView, nbActions;

-(id) initCharacterControllerForModel:(id<CharacterProtocol>) model{
	if (self = [super init]) {
		[self setNbActions:0];
		[self setCharacter:model];
		NSString* characterType = [[self character] characterType];
		[self setSpriteAnimationActive:YES];
		[self setSpriteAnimationMustLoop:YES];
		[self setCharacterPerformingAnimation:NO];
		//moveLeft
		NSMutableArray* tempImagesArray = [[NSMutableArray alloc] init];
		NSString *imageName;
		UIImage *tmpImage = nil;
		NSInteger i=1;
		do {
			imageName = [NSString stringWithFormat:@"%@%@%d%@",characterType,@"MoveLeft",i,@".png"];
			tmpImage = [UIImage imageNamed:imageName];
			if (tmpImage!=nil) {
				[tempImagesArray addObject:tmpImage];
			}
			i = i+1;
		} while (tmpImage!=nil);
		
		[self setSpritesMoveLeft:tempImagesArray];
		[tempImagesArray release];
		i=1;
		
		//moveRight
		tempImagesArray = [[NSMutableArray alloc] init];
		do {
			imageName = [NSString stringWithFormat:@"%@%@%d%@",characterType,@"MoveRight",i,@".png"];
			tmpImage = [UIImage imageNamed:imageName];
			if (tmpImage!=nil) {
				[tempImagesArray addObject:tmpImage];
			}
			i = i+1;
		} while (tmpImage!=nil);
		
		[self setSpritesMoveRight:tempImagesArray];
		[tempImagesArray release];
		i=1;
		
		//selected
		tempImagesArray = [[NSMutableArray alloc] init];
		do {
			imageName = [NSString stringWithFormat:@"%@%@%d%@",characterType,@"Selected",i,@".png"];
			tmpImage = [UIImage imageNamed:imageName];
			if (tmpImage!=nil) {
				[tempImagesArray addObject:tmpImage];
			}
			i = i+1;
		} while (tmpImage!=nil);
		
		
		[self setSpritesSelected:tempImagesArray];
		[tempImagesArray release];
		i=1;
		
		
		
		//stand
		tempImagesArray = [[NSMutableArray alloc] init];
		do {
			imageName = [NSString stringWithFormat:@"%@%@%d%@",characterType,@"Stand",i,@".png"];
			tmpImage = [UIImage imageNamed:imageName];
			if (tmpImage!=nil) {
				[tempImagesArray addObject:tmpImage];
			}
			i = i+1;
		} while (tmpImage!=nil);
		
		
		[self setSpritesStand:tempImagesArray];
		[tempImagesArray release];
		i=1;
		
		//attack
		tempImagesArray = [[NSMutableArray alloc] init];
		
		do {
			imageName = [NSString stringWithFormat:@"%@%@%d%@",characterType,@"Attack",i,@".png"];
			tmpImage = [UIImage imageNamed:imageName];
			if (tmpImage!=nil) {
				[tempImagesArray addObject:tmpImage];
			}
			i = i+1;
		} while (tmpImage!=nil);
		
		
		[self setSpritesAttack:tempImagesArray];
		[tempImagesArray release];
		
		[self setCurrentAnim:[self spritesStand]];
		
		UIView* emptyView = [[CharacterView alloc] initWithFrame:CGRectMake(0.0, 0.0, [[[self currentAnim] objectAtIndex:0] size].width, [[[self currentAnim] objectAtIndex:0] size].height+4) andController:self];
		[self setView:emptyView];
		[emptyView release];
		
		
		UIImageView* initialView = [[RPGImageView alloc] init];
		[self setIndexOfCurrentImage:-1];
		[self setCurrentFrameView:initialView];
		[[self view] addSubview:[self currentFrameView]];
		[[self currentFrameView] sizeToFit];
		[initialView release];
		CharacterBattleAnimationController* tmpAnimationController = [[CharacterBattleAnimationController alloc] initWithCharacter:self];
		[self setAnimationController:tmpAnimationController];
		[tmpAnimationController release];
		SEL selectorNextFrame = @selector(nextFrame);
		NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)1 target:(id)self selector:(SEL)selectorNextFrame userInfo:(id)self repeats:(BOOL)YES];
		[self setAnimationTimer:timer];
		LifeBarViewController* lifeBars = [[LifeBarViewController alloc] initWithMaxLife:[[self character] maxHP] andCurrentLife:[[self character] currentHP] andCurrentMana:[[self character] maxMP] andCurrentMana:[[self character] currentMP]];
		CGPoint characterCenter = [[self view] center];
		CGSize viewFrame = [[self view] frame].size;
		CGPoint centerLifeBar = CGPointMake(characterCenter.x,characterCenter.y+(viewFrame.height/2));
		[[lifeBars view] setCenter:centerLifeBar];
		[[self view] addSubview:[lifeBars view]];
		[self setLifeBarsController:lifeBars];
		[lifeBars release];
	}
    return self;
}

-(void) nextFrame{
	if([self spriteAnimationActive]){
		if ([self indexOfCurrentImage] < -1) {
			[self setIndexOfCurrentImage:-1];
		}
		NSInteger nextId = [self indexOfCurrentImage]+1;
		BOOL begining = ([self indexOfCurrentImage] == -1);
		NSInteger imagesCount = [[self currentAnim] count];
		if(imagesCount == nextId){
			nextId = 0;
		}
		if (!begining && ![self spriteAnimationMustLoop] && nextId == 0) {
			[self setSpriteAnimationActive:NO];
			[[self targetForSelectorSpriteAnimationEnded] performSelector:[self selectorSpriteAnimationEnded]];
		}
		else {
			[[self currentFrameView] setImage:[[self currentAnim] objectAtIndex:nextId]];
			[[self currentFrameView] sizeToFit];
			//[[self characterView] setCurImage:[[self images] objectAtIndex:nextId]];
		}
		[self setIndexOfCurrentImage:nextId];
		if ([self currentAnim]==[self spritesStand] && [[self character] isSelected]) {
			[self animateSelected];
		}
		else if ([self currentAnim]==[self spritesSelected] && ![[self character] isSelected]) {
			[self animateStand];
		}
	}
}

-(void) trySelecting{
	[character trySelecting];
}

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
 [super viewDidLoad];
 }
 */
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

-(void) executeAttackWithNSValue:(NSValue*) targetLocation{
	[self executeAttack:[targetLocation CGPointValue]];
}

-(void) executeAttack:(CGPoint) targetLocation{
	/*if (![self characterPerformingAnimation]){
	 [self setCharacterPerformingAnimation:YES];
	 [self setOriginalPosition:[[self view] center]];
	 SEL selectorAttackPhase2 = @selector(executeAttackPhase2);
	 [self moveCharacter:targetLocation :selectorAttackPhase2];
	 }*/
	[[self animationController] executeAttackToPoint:targetLocation];
}

-(void) executeAttackPhase2{
	SEL selectorAttackPhase3 = @selector(executeAttackPhase3);
	[self animateAttackOnceWithSelectorSpriteAnimationEnded:selectorAttackPhase3];
}

-(void) executeAttackPhase3{
	SEL selectorAnimateStand = @selector(animateStand);
	[self moveCharacter:[self originalPosition] :selectorAnimateStand];
}

-(void) moveTo:(CGPoint) destination{
	while ([self characterPerformingAnimation]) {
		
	}
	SEL selectorAnimateStand = @selector(animateStand);
	[self moveCharacter:destination :selectorAnimateStand];
}

-(void) moveCharacter:(CGPoint) destination :(SEL) endAnimationSelector{
	[UIView beginAnimations:nil context:NULL];
	SEL selectorAnimationEnded = endAnimationSelector;
	SEL selectorAnimateMove;
	if (destination.x>[[self view] center].x) {
		selectorAnimateMove = @selector(animateMoveRight);
	}
	else {
		selectorAnimateMove = @selector(animateMoveLeft);
	}
	[UIView setAnimationDelegate:self];
	[UIView setAnimationWillStartSelector:selectorAnimateMove];
	[UIView setAnimationDidStopSelector:selectorAnimationEnded];
	[UIView setAnimationDuration:2];
	[[self view] setCenter:destination];
	[UIView commitAnimations];
}

-(void) animateDeath{
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDuration:damageViewTravelDuration];
	[[self view] setAlpha:0.0];
	[UIView commitAnimations];
}

-(void) animateSelected{
	if ([self currentAnim] != [self spritesSelected]){
		[self stopAnimationTimer];
		[self setIndexOfCurrentImage:-1];
		[self setSpriteAnimationMustLoop:YES];
		[self setCurrentAnim:[self spritesSelected]];
		[self resetTimerWithInterval:animateSelectedInterval];
		[self setCharacterPerformingAnimation:NO];
		[self fireAnimationTimer];
	}
}


-(void) animateStand{
	if ([self currentAnim] != [self spritesStand]){
		[self stopAnimationTimer];
		[self setIndexOfCurrentImage:-1];
		[self setSpriteAnimationMustLoop:YES];
		[self setCurrentAnim:[self spritesStand]];
		[self resetTimerWithInterval:animateStandInterval];
		[self setCharacterPerformingAnimation:NO];
		[self fireAnimationTimer];
	}
}

-(void) animateMoveLeft{
	if ([self currentAnim] != [self spritesMoveLeft]){
		[self stopAnimationTimer];
		[self setIndexOfCurrentImage:-1];
		[self setSpriteAnimationMustLoop:YES];
		[self setCurrentAnim:[self spritesMoveLeft]];
		[self resetTimerWithInterval:animateMoveLeftInterval];
		[self fireAnimationTimer];
	}
}

-(void) animateMoveRight{
	if ([self currentAnim] != [self spritesMoveRight]){
		[self stopAnimationTimer];
		[self setIndexOfCurrentImage:-1];
		[self setSpriteAnimationMustLoop:YES];
		[self setCurrentAnim:[self spritesMoveRight]];
		[self resetTimerWithInterval:animateMoveRightInterval];
		[self fireAnimationTimer];
	}
}

-(void) select{
	if ([self currentAnim]==[self spritesStand]) {
		[self animateSelected];
	}
}

-(void) unselect{
	if ([self currentAnim]==[self spritesSelected]) {
		[self animateStand];
	}
}

-(void) fireAnimationTimer{
	[[self animationTimer] fire];
}

-(void) changeAttackTargetPosition:(CGPoint) newTargetPosition{
	[[self animationController] chanceAttackdestination:newTargetPosition];
}
-(void) animateAttackOnceWithSelectorSpriteAnimationEnded:(SEL) selector{
	[self animateAttackOnceWithSelectorSpriteAnimationEnded:selector onTarget:self];
}

-(void) animateAttackOnceWithSelectorSpriteAnimationEnded:(SEL) selector onTarget:(id)selectorTarget;{
	[self stopAnimationTimer];
	[self setSelectorSpriteAnimationEnded:selector];
	[self setTargetForSelectorSpriteAnimationEnded:selectorTarget];
	[self setSpriteAnimationMustLoop:NO];
	[self setIndexOfCurrentImage:-1];
	[self setCurrentAnim:[self spritesAttack]];
	[self resetTimerWithInterval:attackAnimationTimeInterval];
}

-(void) stopAnimationTimer{
	[[self animationTimer] invalidate];
}

-(void) resetTimerWithInterval:(NSTimeInterval) interval{
	[self setSpriteAnimationActive:YES];
	SEL selectorNextFrame = @selector(nextFrame);
	NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:interval target:(id)self selector:(SEL)selectorNextFrame userInfo:(id)self repeats:(BOOL)YES];
	[self setAnimationTimer:timer];
}

-(void) showDamages:(NSInteger) damages{
	if ([self currentDamagesView]==nil) {
		UITextView* damageView = [[UITextView alloc] initWithFrame:CGRectMake(0.0, 0.0, [[self view] frame].size.width, textHeight)];
		[damageView setTextAlignment:UITextAlignmentCenter];
		[damageView setBackgroundColor:[UIColor clearColor]];
		CGPoint lifeBarsPosition = [[[self lifeBarsController] view] center];
		[damageView setCenter:lifeBarsPosition];
		CGPoint damageDestination = CGPointMake(lifeBarsPosition.x, lifeBarsPosition.y+damageViewTravelHeight);
		NSString* damagesString = [NSString stringWithFormat:@"%d",damages];
		[damageView setText:damagesString];
		[[self view] addSubview:damageView];
		[self setCurrentDamagesView:damageView];
		// effective animation
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDelegate:self];
		[UIView setAnimationDidStopSelector:@selector(removeDamageView)];
		[UIView setAnimationDuration:damageViewTravelDuration];
		[damageView setCenter:damageDestination];
		[UIView commitAnimations];
		[damageView release];
	}
}

-(void) removeDamageView{
	if ([self currentDamagesView]!=nil) {
		[[self currentDamagesView] removeFromSuperview];
		[self setCurrentDamagesView:nil];
	}
}

-(void) changeHealth:(NSInteger) newHealth{
	[[self lifeBarsController] setCurrentLife:newHealth];
}

-(void) changeMana:(NSInteger) newMana{
	[[self lifeBarsController] setCurrentMana:newMana];
}


-(void) setActionEnded{
	[[[self character] currentBattle] executeCurrentActionNextPhase];
}

- (void)dealloc {
	[self setCharacter:nil];
	[self setAnimationController:nil];
	[self setSpritesMoveLeft:nil];
	[self setSpritesMoveRight:nil];
	[self setSpritesSelected:nil];
	[self setSpritesStand:nil];
	[self setSpritesAttack:nil];
	[self setCurrentAnim:nil];
	[self setAnimationTimer:nil];
	[self setTargetForSelectorSpriteAnimationEnded:nil];
	[self setCurrentFrameView:nil];
	[self setLifeBarsController:nil];
	[self setCurrentDamagesView:nil];
	[super dealloc];
}

@end